package com.lin.project.lininit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.project.lininit.common.ErrorCode;
import com.lin.project.lininit.exception.BusinessException;
import com.lin.project.lininit.model.entity.User;
import com.lin.project.lininit.service.UserService;
import com.lin.project.lininit.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.lin.project.lininit.constant.UserConstant.ADMIN_ROLE;
import static com.lin.project.lininit.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 林怀旭
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2023-05-15 10:37:01
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT="linhuaixu";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账户过短");
        }
        if(userPassword.length()<8 || checkPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }
        //密码和校验密码相同
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次输入密码不一致");
        }
        synchronized (userAccount.intern()){
            //账户不能重复
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("userAccount",userAccount);
            long count=userMapper.selectCount(queryWrapper);
            if(count>0){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号重复");
            }
            //2.加密
            String encryptPassword= DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
            //3.插入数据
            User user=new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            boolean save = this.save(user);
            if(!save){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号错误");
        }
        if(userPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码错误");
        }
        //2.加密
        String encryptPassword= DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        //3.查询用户是否存在
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if(user==null){
            log.info("用户登录失败，账号和密码不匹配");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在或密码错误");
        }
        //4.将用户信息存入session
        request.getSession().setAttribute(USER_LOGIN_STATE,user);
        return user;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        User currentUser= (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if(currentUser==null || currentUser.getId()==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long id = currentUser.getId();
        User user = this.getById(id);
        if(user==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        User currentUser= (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        return currentUser!=null && ADMIN_ROLE.equals(currentUser.getUserRole());
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        if(request.getSession().getAttribute(USER_LOGIN_STATE)==null){
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR,"未登录");
        }
        //移除登录状态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

}




